// formPackage/pages/team/inviteCompanyMember/inviteCompanyMember.js
import { loginWxAction, sendApplyAgentCodeAction, saveNickNameAndAvatarAction } from "../../../../service/config"
import { companyInviteEmployeeEnter } from "../../../../service/team_service"
// imTODO
import { updateUserImInfo } from "../../../../service/newIm_service"
import debounce from "../../../../tools/debounce"
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeStyle: "",
    couponCodeBtnStatus: false,
    couponCodeBtnTitle: "获取验证码",
    snsMsgWait: 60,//倒计时
    formData: {
      "code": "",
      "companyNumber": "",
      "name": "",
      "phone": "",
      "role": "",
      "weChat": "",//微信号

    },
    showSinglePop: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      'formData.companyNumber': options.companyNumber,
    })
    this.userWxLogin();
  },

  //用户登陆授权等:
  userWxLogin() {
    loginWxAction().then((res => {
      console.log("JJLog:登录返回:" + JSON.stringify(res));
      let data = res.data.data;
      if (res.code == 200) {
        app.globalData.nickName = data.nickName;
        app.globalData.avatar = data.avatar;
        app.globalData.name = data.name || "";
        app.globalData.phone = data.phone || "";
        app.globalData.isLogin = data.isLogin;
        app.globalData.userId = data.id;
        app.globalData.qrCode = data.qrCode || "";
        app.globalData.isAuthUserInfo = data.isAuthUserInfo;
        app.globalData.weChat = data.weChat || "";
        app.globalData.roleName = data.roleName || "";
        app.globalData.companyName = data.companyName || "";
        app.globalData.companyNumber = data.companyNumber || "";
        app.globalData.isBindMp = data.isBindMp;
        app.globalData.roleType = data.roleType || 1
      }
    })).catch(err => {
      console.error("JJLog:userWxLogin", err);

    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
  },
  singleSelectPop() {
    this.setData({
      showSinglePop: true,
    })
  },

  singlePopSelectCallback(e) {
    // console.log("JJLog:hfh :" + JSON.stringify(e));
    let result = e.detail.result;
    this.setData({
      'formData.role': result.label,
      showSinglePop: false
    })
  },
  //确定提交
  submitInfoAction() {
    let data = this.data.formData;

    if (!data.name) {
      wx.showToast({
        title: '请输入联系人姓名',
        icon: "none"
      })
      return;
    }
    if (!data.phone) {
      wx.showToast({
        title: '请输入联系人手机号',
        icon: "none"
      })
      return;
    }
    if (!data.code) {
      wx.showToast({
        title: '请输入验证码',
        icon: "none"
      })
      return;
    }
    // if (!data.weChat) {
    //   wx.showToast({
    //     title: '请输入微信号',
    //     icon: "none"
    //   })
    //   return;
    // }
    if (!data.role) {
      wx.showToast({
        title: '请选择入驻角色',
        icon: "none"
      })
      return;
    }
    if (app.globalData.isAuthUserInfo) {
      console.log("JJLog:调教数据:" + JSON.stringify(this.data.formData));
      debounce(this.companyInviteEmployeeEnter);
    } else {
      wx.getUserProfile({
        desc: "请求您的微信头像昵称授权",
        success: res => {
          console.log("JJLog:微信授权:" + JSON.stringify(res));
          saveNickNameAndAvatarAction(res.userInfo.nickName, res.userInfo.avatarUrl)
          // imTODO
          this.updateUserImInfo(res.userInfo.nickName, res.userInfo.avatarUrl)
          this.companyInviteEmployeeEnter();

        },
        fail: err => {
          console.log("JJLog:获取微信信息失败:" + JSON.stringify(err));
          wx.showToast({
            title: '授权才能继续',
            icon: "none"
          })
        }
      })
    }


  },
  companyInviteEmployeeEnter() {
    wx.showLoading();
    companyInviteEmployeeEnter(this.data.formData).then(res => {
      wx.hideLoading();
      console.log("JJLog:审核列表是:" + JSON.stringify(res));
      if (res.code == 200) {
        wx.showToast({
          title: '入驻成功',
          icon: "success"
        })
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/home/home',
          })
        }, 2000);
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "查询失败",
        icon: "none"
      })
      console.error("JJLog:companyInviteEmployeeEnter", err);
    })
  },

  bindPhoneInputValue(e) {
    // console.log("JJLog:e==:" + JSON.stringify(e));
    this.setData({
      'formData.phone': e.detail.value
    })
  },
  // imTODO 更新im的资料
  updateUserImInfo(name, avatar) {
    let params = {
      account: app.globalData.openId,
      name: name,
      avatar: avatar,
      appId: app.globalData.imAppId,
    }
    updateUserImInfo(params).then(res => {
      if (res.code == 200) {
        console.log("JJLog:更新IM资料成功=====");
      }
    }).catch(err => {
      console.error("JJLog:更新IM资料失败===:", err);
    })
  },

  /** 发送验证码 */
  clickSendCode() {
    if (this.data.couponCodeBtnStatus) {
      return;
    }
    let that = this;
    //点击了发送按钮，就先禁用掉这个按钮点击
    this.setData({
      couponCodeBtnStatus: true,
    })
    //调用发送验证码接口:
    let phone = this.data.formData.phone;
    let warn = null;
    if (phone == '') {
      warn = "号码不能为空";
    } else if (phone.trim().length != 11 || !/^1[3|4|5|6|7|8|9]\d{9}$/.test(phone)) {
      warn = "手机号格式不正确";
    } else {
      sendApplyAgentCodeAction(phone).then((data) => {
        //当手机号正确的时候提示用户短信验证码已经发送
        wx.showToast({
          title: '短信验证码已发送',
          icon: 'none',
          duration: 2000
        });
        let inter = setInterval(function () {
          this.setData({
            couponCodeBtnStatus: true,
            couponCodeBtnTitle: this.data.snsMsgWait + 's后重发',
            snsMsgWait: this.data.snsMsgWait - 1
          });
          if (this.data.snsMsgWait < 0) {
            clearInterval(inter)
            this.setData({
              couponCodeBtnTitle: '重新发送',
              snsMsgWait: 60,
              couponCodeBtnStatus: false
            });
          }
        }.bind(this), 1000);

      }).
        catch((err) => {
          that.setData({
            couponCodeBtnStatus: false
          })
          wx.showToast({
            icon: 'none',
            title: err,
          })
        })


    }
    if (warn != null) {
      wx.showModal({
        title: '提示',
        content: warn
      })
      that.setData({
        couponCodeBtnStatus: false
      })
      return;
    }

  },

  //单项输入回调:
  inputCellChange(e) {
    let type = e.detail.key;
    let changeValue = `formData.${type}`;
    this.setData({
      [changeValue]: e.detail.value
    })
  },

  backHomeAction() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },





  singlePopHide() {
    this.setData({
      showSinglePop: false,
    })
  },

})